#!/usr/bin/python
#
# Copyright 2010 Tipin Chang, tipinchang@gmail.com. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License):
#   http://www.apache.org/licenses/LICENSE-2.0
#
# The software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied.
#

'''Examples of using OpenBatch to peform various batch processing jobs
'''
__author__ = "tipinchang@gmail.com (Tipin Chang)"

import platform
import datetime
from openbatch import *

#======================================================================
# Example batch programs
#======================================================================
def example1():
    # Open template document: "sample.doc" or "sample.odt" depending
    # on the running platform
    if platform.system() == 'Linux':
        docExtension = 'odt'
        template = OpenTextDoc("sample.odt")
    elif platform.system() == 'Windows':
        docExtension = 'doc'
        template = WordDoc("sample.doc")
    # Replace text in the template document according to 'dict'
    dict = {"$FullName$":"Mr. Somebody",
            "$Family$":", your wife, and two kids"}
    template.replaceText(dict)
    # Save the replaced template document to a new file "temp1.xxx"
    template.saveAs("temp1.%s" % docExtension)
    template.close()

def example2():
    dict = {"$FullName$":"Mr. Somebody",
            "$Family$":", your wife, and two kids"}
    # Open a template HTML file, "sample.html"
    htmlDoc = FileHTML("sample.html")
    # Replace text according to 'dict'
    htmlDoc.replaceText(dict)
    # Open an image "sample.jpg" file
    image = FileDoc("sample.jpg")
    # Open an audio  "sample.mp3" file
    audio = FileDoc("sample.mp3")
    # Create an email object with html as message, and one image attachement
    email = EmailDoc("nobody@nowhere.com", "RecipientEmail",
                     "Your mail subject", htmlDoc, [image, audio])
    # Create a Gmail SMTP server connection
    server = GmailServer("YourGmailAccount", "YourGmailPassword")
    # Send email via Gmail SMTP server
    server.send(email)

def example3():
    # check running platform and set document file extension
    if platform.system() == 'Linux':
        docExtension = 'odt'
    elif platform.system() == 'Windows':
        docExtension = 'doc'
    else:
        raise ObErr("unsupported platform:%s" % platform.system())
    # Create a OpenSpreadsheet object from file "ParenChild.ods"
    spreadsheet = OpenSpreadsheet("sample.ods")
    docId = 1
    # iterate thru each row (as a 'dict') in the spreadsheet
    for dict in spreadsheet:
        # Compose $FullName$ from $salute$ and $name$
        salute = dict['$salute$']
        if salute != '':
            salute += ' '
        # Add new mapping of $FullName$ and $Date$ to 'dict'
        dict['$FullName$'] = salute + dict['$name$']
        dict['$Date$'] = ("%s" % datetime.date.today())
        # Compose $Family$ from $spouse$, $child?$ into an English
        # gramatically correct way (e.g. "sprouse, child1 and child2")
        spouse = dict['$spouse$']
        children = []
        for no in range(1,5):
            child = dict['$child%d$'%no]
            if child=='':
                break
            children.append(child)
        if spouse == '':
            family = ''
        elif len(children) == 0:
            family = 'and ' + spouse
        else:
            family = ', ' + spouse
            for child in children[:-1]:
                family += ', ' + child
            family += ' and ' + children[-1]
        # Add new $Family$ mapping to 'dict'
        dict['$Family$'] = family
        # Load the template document
        if docExtension == 'odt':
            template = OpenTextDoc("sample.odt")
        else:
            template = WordDoc("sample.doc")
        # Replace all occurrences of 'key' by its corresponding value
        # specified by 'dict'
        template.replaceText(dict)
        # Save the text replaced document into another file
        template.saveAs("temp%d.%s" % (docId, docExtension))
        template.close()
        docId += 1

if __name__ == '__main__':
    # invoke the batch processing program
    #example1()
    #example2()
    example3()
    #pass
    
